<?php
require('header.php');
require ('inStock.php');

if (!isset($_POST['choice'])) {
	?>
	<form method="post" action="">
		<h3>Browse Parts</h3>
		<br> Order by: <select name='choice'>
			<option value='name'>Name</option>
			<option value='price'>Price</option>
			<option value='category'>Category</option>
			<option value='type'>Type</option>
			<option value='car'>Car</option>
			<option value='manufacturer'>Manufacturer</option>
			<option value='refurbished'>Refurbished</option>
		  </select>
		<br><input type='submit' name='submit' value='submit' />
	</form>
	<?php
} else {
	$order = ($_POST['choice'] == 'refurbished' ? " DESC" : " ASC");
	if($_POST['choice'] == 'car') {
		$query = "SELECT * FROM item INNER JOIN car ON item.car=car.car_id ORDER BY car.make " . $order . ", car.model, car.year";
	} else {
		$query = "SELECT * FROM item INNER JOIN car ON item.car=car.car_id ORDER BY " . $_POST['choice'] . $order;
	}
	// echo $query;
	if ($result = mysqli_query($con, $query)) {
		if (mysqli_num_rows($result) > 0) {
			while ($row = mysqli_fetch_array($result)) {
				$availability = 0;
				if (inStock($row['part_no'], $con)) {
					$query = "SELECT SUM(quantity) FROM stock WHERE itemID=" . $row['part_no'];
					if (! $res = mysqli_query($con, $query))  echo mysqli_error($con) . "<br>";
					$res = mysqli_fetch_array($res);
					$availability = $res[0];
				}
				echo <<<EOT
				<br>Name: $row[name]
				<br>Price: $row[price]
				<br>Availability: $availability
				<br>Category: $row[category]
				<br>Type: $row[type]
				<br>Car: $row[make] $row[model] $row[year]
				<br>Manufacturer: $row[manufacturer]
				<br>Refurbished:
EOT;
				if($row['refurbished']) {
					echo " Yes";
				} else {
					echo " No";
				}
				echo "<br><strong><a href='cart.php?id=" . $row['part_no'] . "&action=add'>Add to Cart</a></strong><br><br>";
				
			}
		} else {
			echo "There were no results for this query. Please go back and try again.";
		}
	} else {
		echo "There was an error: " . mysqli_error($con) . "<br>";
	}
}


require('footer.php');
?>